package belf.migrate.engine.job.structure.helper;

import belf.migrate.api.common.DatabaseCompatibility;
import belf.migrate.api.common.DatabaseIdentifier;
import belf.migrate.api.exception.CatalogException;
import belf.migrate.api.exception.ViewNotExistException;
import belf.migrate.api.model.QualifiersModel;
import belf.migrate.api.table.schema.Catalog;
import belf.migrate.api.table.schema.TablePath;
import belf.migrate.api.taskconf.JobContext;
import belf.migrate.api.type.DbObjectType;
import belf.migrate.api.type.LogLevelType;
import belf.migrate.api.util.EngineConf;
import belf.migrate.api.util.PostLog;
import belf.migrate.api.job.Job;
import belf.migrate.engine.job.JobResult;
import belf.migrate.engine.job.JobResultItem;
import belf.migrate.api.util.ExceptionUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.time.DateFormatUtils;

import java.util.Date;
import java.util.List;

import static belf.migrate.api.job.JobCode.*;

@Slf4j
public class CreateViewTool extends SqlTransformTool {
    public CreateViewTool(Job job) {
        super(job);
    }

    public CreateViewTool(Job job, JobContext jobContext) {
        super(job, jobContext);
    }

    @Override
    public JobResult run() {
        PostLog.sendLogModel(
                job.getJobId(),
                job.getTask().getTaskType().getName(),
                "创建视图开始！",
                LogLevelType.INFO.getType(),
                EXECUTING,
                jobContext.getProgress());
        JobResult jobResult = new JobResult(SUCCESS, "创建选中的视图成功");
        Catalog sourceCatalog = jobContext.getSourceCatalog();

        try {
            List viewNames; //待创建的视图名称列表
            // 若限定了要处理的视图名称
            if (job.getMissions() != null && !job.getMissions().isEmpty()) {
                viewNames = job.getMissions();
            } else {
                viewNames = sourceCatalog.listViewNames(jobContext.getTaskConf().getSourceConf().getDatabaseName(),
                        jobContext.getTaskConf().getSourceConf().getSchemaName());
            }

            if (!CollectionUtils.isEmpty(viewNames)) {
                transform(viewNames, jobResult);
            }
        } catch (CatalogException e) {
//            e.printStackTrace();
        }

        if (jobResult.getFailtures() > 0) {
            jobResult.setCode(CREATE_VIEW_ERROR);
            jobResult.setMessage("创建选中的视图失败");
            log.error("Create Some Views Of {} Failed.", jobContext.getValidSinkDatabase());
        } else {
            log.info("Create All Views Of {} Successfully.", jobContext.getValidSinkDatabase());
        }

        PostLog.sendLogModel(
                job.getJobId(),
                job.getTask().getTaskType().getName(),
                "创建视图结束！",
                LogLevelType.INFO.getType(),
                EXECUTING,
                jobContext.getProgress());
        return jobResult;
    }

    protected JobResultItem process(Object object) {
        String viewName = (String)object;
        Catalog sourceCatalog = jobContext.getSourceCatalog();
        Catalog sinkCatalog = jobContext.getSinkCatalog();
        QualifiersModel sourceQualifiersModel = getSourceQualifiersModel();
        QualifiersModel sinkQualifiersModel = getSinkQualifiersModel();
        String startTime = DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss.SSS");

        TablePath sourceViewPath = TablePath.of(jobContext.getTaskConf().getSourceConf().getDatabaseName(),
                jobContext.getTaskConf().getSourceConf().getSchemaName(),
                viewName,
                sourceQualifiersModel);
        TablePath sinkViewPath = TablePath.of(jobContext.getTaskConf().getSinkConf().getDatabaseName(),
                jobContext.getTaskConf().getSinkConf().getSchemaName(),
                viewName,
                sinkQualifiersModel);

        JobResultItem jobResultItem = new JobResultItem(viewName, sinkViewPath.getCaseTableName(), SUCCESS, "创建视图" + viewName + "成功");
        jobResultItem.setType(DbObjectType.VIEW.getTypeName());
        jobResultItem.setStartTime(startTime);

        String ddl = null;
        String sinkCreateViewDDL = null;
        SqlResponse sqlResponse = null;
        try {
            ddl = sourceCatalog.showCreateView(sourceViewPath);

            String promptTempalate = """
                    请将以下%s创建视图的SQL语句转为%s创建视图的SQL语句：\n
                    %s\n
                    %s
                    """;
            String srcDbCatalog = DatabaseIdentifier.name(sourceCatalog.name());
            String targetDbCatalog = DatabaseIdentifier.name(sinkCatalog.name());
            String requirement = PromtHelper.requirement(jobContext.getTaskConf().getSourceConf().getCatalogName(),
                    jobContext.getTaskConf().getSinkConf().getCatalogName(),
                    jobContext.getTaskConf().getSinkConf().getSchemaName(),
                    sinkQualifiersModel,
                    DbObjectType.VIEW);
            //是否启用数据库的语法兼容性？比如达梦极大兼容Oracle
            boolean dbCompatible = EngineConf.getInstance().getBoolean("llm.enable.db.compatible");
            String prompt = String.format(promptTempalate,
                    srcDbCatalog,
                    dbCompatible? DatabaseCompatibility.name(sinkCatalog.name()):targetDbCatalog,
                    ddl,
                    requirement);
            log.info("转换视图的提示词：\n{}", prompt);
            sqlResponse = SqlAgent.post(jobContext.getTaskConf().getAiModel(), prompt);
            if (null != sqlResponse) {
                sinkCreateViewDDL = sqlResponse.getSql();
                log.info("Converted View DDL: \n", sinkCreateViewDDL);
                sinkCatalog.executeSql(sinkViewPath, sinkCreateViewDDL);
                jobResultItem.setSinkDdl(sinkCreateViewDDL);
                log.info("Create view successfully");
            }
        } catch (ViewNotExistException e) {
            log.error("Create view error:{} is not existed!", viewName);
            PostLog.sendLogModel(
                    job.getJobId(),
                    job.getTask().getTaskType().getName(),
                    "源库" + jobContext.getTaskConf().getSourceConf().getCatalogName() + "视图不存在：" + viewName,
                    LogLevelType.ERROR.getType(),
                    EXECUTING,
                    jobContext.getProgress());
            String endTime = DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss.SSS");
            log.error("Create view successfully:\n{}", sinkCreateViewDDL);
            return new JobResultItem(viewName,
                    sinkViewPath.getCaseTableName(),
                    CREATE_VIEW_ERROR,
                    "源库" + jobContext.getTaskConf().getSourceConf().getCatalogName() + "视图不存在：" + viewName,
                    ExceptionUtils.toString(e),
                    DbObjectType.VIEW.getTypeName(),
                    startTime,
                    DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss.SSS"),
                    ddl,
                    sinkCreateViewDDL);
        } catch (CatalogException e) {
            log.error("Create view error:\n{}", ExceptionUtils.toString(e));
            String endTime = DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss.SSS");
            PostLog.sendLogModel(
                    job.getJobId(),
                    job.getTask().getTaskType().getName(),
                    String.format("创建视图%s失败, SQL错误：%s", viewName, e.getCause().getMessage()),
                    LogLevelType.ERROR.getType(),
                    EXECUTING,
                    jobContext.getProgress());
            String errorTips = null;
            if (sqlResponse != null) {
                // 返回大模型给出的sql转化理由
                errorTips = String.join("\n", sqlResponse.getReasons());
            }
            return new JobResultItem(viewName,
                    sinkViewPath.getCaseTableName(),
                    CREATE_VIEW_ERROR,
                    String.format("创建视图%s失败, SQL错误：%s", viewName, e.getCause().getMessage()),
                    ExceptionUtils.toString(e.getCause()),
                    DbObjectType.VIEW.getTypeName(),
                    startTime,
                    endTime,
                    ddl,
                    sinkCreateViewDDL,
                    errorTips);
        }

        PostLog.sendLogModel(
                job.getJobId(),
                job.getTask().getTaskType().getName(),
                String.format("创建视图 %s 成功", viewName),
                LogLevelType.INFO.getType(),
                EXECUTING,
                jobContext.getProgress());

        jobResultItem.setEndTime(DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss.SSS"));
        return jobResultItem;
    }
}
